<template>
	<view class="join-chatroom-page">
		<!-- 顶部搜索栏 -->
		<view class="search-bar">
			<up-search 
				shape="round" 
				v-model="searchValue" 
				@search="searchChatroom" 
				@clear="searchClear"
				placeholder="搜索聊天室"
				:clearabled="true"
			></up-search>
		</view>

		<!-- 聊天室列表 -->
		<view class="chatroom-content">
			<scroll-view 
				scroll-y 
				class="scroll-container" 
				@scrolltolower="loadMore"
				:refresher-enabled="true"
				:refresher-triggered="refreshing"
				@refresherrefresh="onRefresh"
				@refresherrestore="onRestore"
			>
				<!-- 骨架屏 -->
				<view class="skeleton-container" v-if="loading && chatrooms.length === 0">
					<view class="skeleton-item" v-for="i in 5" :key="i">
						<view class="skeleton-avatar skeleton-animate"></view>
						<view class="skeleton-content">
							<view class="skeleton-title skeleton-animate"></view>
							<view class="skeleton-text skeleton-animate"></view>
						</view>
					</view>
				</view>

				<!-- 聊天室列表 -->
				<view class="chatroom-list" v-else-if="chatrooms && chatrooms.length > 0">
					<view 
						class="chatroom-card"
						v-for="room in chatrooms"
						:key="room.roomId"
					>
						<image class="room-avatar" :src="room.avatar" mode="aspectFill" />
						<view class="room-content">
							<view class="room-header">
								<text class="room-name">{{ room.roomName }}</text>
								<!-- 已加入 -->
								<view class="status-badge joined" v-if="room.joinStatus === 'joined'">
									<up-icon name="checkmark-circle" size="14" color="#52c41a"></up-icon>
									<text>已加入</text>
								</view>
								<!-- 待审核 -->
								<view class="status-badge pending" v-else-if="room.joinStatus === 'pending'">
									<up-icon name="clock" size="14" color="#faad14"></up-icon>
									<text>待审核</text>
								</view>
								<!-- 未加入 - 显示加入按钮 -->
								<view 
									class="join-btn" 
									v-else
									@click.stop="handleJoinRoom(room)"
								>
									<up-icon name="plus" size="14" color="#fff"></up-icon>
									<text>加入</text>
								</view>
							</view>
							<text class="room-desc">{{ room.roomDesc }}</text>
							<view class="room-meta">
								<text class="meta-item">
									<up-icon name="account" size="12" color="#999"></up-icon>
									{{ room.memberCount }}人
								</text>
								<text class="meta-item">
									<up-icon name="eye" size="12" color="#999"></up-icon>
									{{ room.onlineCount }}在线
								</text>
							</view>
						</view>
					</view>

					<!-- 加载更多提示 -->
					<view class="load-more" v-if="hasMore">
						<up-loading-icon v-if="loadingMore" size="20" />
						<text v-else class="load-more-text">上拉加载更多</text>
					</view>
					<view class="no-more" v-else>
						<text class="no-more-text">没有更多了</text>
					</view>
				</view>

				<!-- 空状态 -->
				<view class="empty-state" v-else-if="!loading && chatrooms.length === 0">
					<up-icon name="chat" size="80" color="#cccccc"></up-icon>
					<text class="empty-text">暂无聊天室</text>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { mockGetAllChatrooms, mockJoinChatroom } from '../../server/mock.js';

// 响应式数据
const searchValue = ref('');
const chatrooms = ref([]);
const loading = ref(true);
const loadingMore = ref(false);
const hasMore = ref(true);
const pageNum = ref(1);
const pageSize = ref(20);
const refreshing = ref(false);

// 页面加载时获取数据
onMounted(() => {
	getChatroomList();
});

/**
 * 获取聊天室列表（全部聊天室）
 */
const getChatroomList = async () => {
	if (pageNum.value === 1) {
		loading.value = true;
	}
	
	try {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			keyword: searchValue.value || undefined
		};

		const res = await mockGetAllChatrooms(params);
		
		if (res.code === 200) {
			const newChatrooms = res.data.list || [];
			const total = res.data.total || 0;

			if (pageNum.value === 1) {
				chatrooms.value = newChatrooms;
			} else {
				chatrooms.value.push(...newChatrooms);
			}

			// 判断是否还有更多数据
			hasMore.value = chatrooms.value.length < total;
		}
	} catch (error) {
		console.error('获取聊天室列表失败:', error);
		if (pageNum.value === 1) {
			chatrooms.value = [];
		}
	} finally {
		loading.value = false;
	}
};

/**
 * 搜索聊天室
 */
const searchChatroom = () => {
	pageNum.value = 1;
	hasMore.value = true;
	getChatroomList();
};

/**
 * 清除搜索
 */
const searchClear = () => {
	searchValue.value = '';
	pageNum.value = 1;
	hasMore.value = true;
	getChatroomList();
};

/**
 * 点击聊天室卡片（查看详情）
 */
const handleRoomClick = (roomId) => {
	// 可以跳转到聊天室详情页查看信息
	uni.showToast({
		title: '查看聊天室详情',
		icon: 'none'
	});
};

/**
 * 加入聊天室
 */
const handleJoinRoom = async (room) => {
	try {
		uni.showLoading({ title: '加入中...' });
		
		const res = await mockJoinChatroom(room.roomId);

		uni.hideLoading();

		if (res.code === 200) {
			uni.showToast({
				title: '加入成功',
				icon: 'success'
			});
			
			// 更新当前聊天室的状态
			const index = chatrooms.value.findIndex(r => r.roomId === room.roomId);
			if (index !== -1) {
				chatrooms.value[index].joinStatus = 'joined';
			}
		} else {
			uni.showToast({
				title: res.message || '加入失败',
				icon: 'none'
			});
		}
	} catch (error) {
		uni.hideLoading();
		console.error('加入聊天室失败:', error);
		uni.showToast({
			title: '加入失败',
			icon: 'none'
		});
	}
};

/**
 * 加载更多
 */
const loadMore = () => {
	if (!hasMore.value || loadingMore.value || loading.value) return;
	
	loadingMore.value = true;
	pageNum.value += 1;
	getChatroomList().finally(() => {
		loadingMore.value = false;
	});
};

/**
 * 下拉刷新
 */
const onRefresh = async () => {
	refreshing.value = true;
	pageNum.value = 1;
	hasMore.value = true;
	
	try {
		await getChatroomList();
	} finally {
		setTimeout(() => {
			refreshing.value = false;
		}, 300);
	}
};

/**
 * 刷新恢复
 */
const onRestore = () => {
	refreshing.value = false;
};
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';
@import '../../styles/mixins.scss';

.join-chatroom-page {
	width: 100%;
	min-height: 100vh;
	display: flex;
	flex-direction: column;
	background: $bg-page;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
}

// 搜索栏
.search-bar {
	padding: $spacing-base;
	background: $bg-card;
	border-bottom: 1px solid $border-light;
}

// 内容区
.chatroom-content {
	flex: 1;
	overflow: hidden;
	
	.scroll-container {
		height: 100%;
	}
}

// 骨架屏
.skeleton-container {
	padding: $spacing-base;
	
	.skeleton-item {
		display: flex;
		padding: $spacing-base;
		margin-bottom: $spacing-base;
		background: $bg-card;
		border-radius: $radius-base;
		
		.skeleton-avatar {
			width: 60px;
			height: 60px;
			border-radius: $radius-base;
			background: $bg-page;
			flex-shrink: 0;
		}
		
		.skeleton-content {
			flex: 1;
			margin-left: $spacing-base;
			
			.skeleton-title {
				height: 18px;
				width: 60%;
				margin-bottom: $spacing-sm;
				background: $bg-page;
				border-radius: $radius-sm;
			}
			
			.skeleton-text {
				height: 14px;
				width: 80%;
				background: $bg-page;
				border-radius: $radius-sm;
			}
		}
	}
}

.skeleton-animate {
	animation: skeleton-loading 1.5s ease-in-out infinite;
}

@keyframes skeleton-loading {
	0%, 100% {
		opacity: 1;
	}
	50% {
		opacity: 0.5;
	}
}

// 聊天室列表
.chatroom-list {
	padding: $spacing-base;
	
	.chatroom-card {
		display: flex;
		padding: $spacing-base;
		margin-bottom: $spacing-base;
		background: $bg-card;
		border-radius: $radius-base;
		box-shadow: $shadow-sm;
		transition: all $transition-fast;
		cursor: pointer;
		
		&:active {
			transform: scale(0.98);
			box-shadow: $shadow-base;
		}
		
		.room-avatar {
			width: 60px;
			height: 60px;
			border-radius: $radius-base;
			flex-shrink: 0;
		}
		
		.room-content {
			flex: 1;
			margin-left: $spacing-base;
			display: flex;
			flex-direction: column;
			
			.room-header {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: $spacing-xs;
				
				.room-name {
					flex: 1;
					font-size: $font-base;
					font-weight: $font-medium;
					color: $text-primary;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
					margin-right: $spacing-sm;
				}
				
				.status-badge {
					display: flex;
					align-items: center;
					gap: 4px;
					padding: 4px $spacing-sm;
					border-radius: $radius-sm;
					font-size: $font-xs;
					flex-shrink: 0;
					
					&.joined {
						background: rgba(82, 196, 26, 0.1);
						color: $success-color;
					}
					
					&.pending {
						background: rgba(250, 173, 20, 0.1);
						color: $warning-color;
					}
				}
				
				.join-btn {
					display: flex;
					align-items: center;
					gap: 4px;
					padding: 4px $spacing-base;
					background: $primary-color;
					color: #fff;
					border-radius: $radius-sm;
					font-size: $font-xs;
					font-weight: $font-medium;
					flex-shrink: 0;
					transition: all $transition-fast;
					
					&:active {
						transform: scale(0.95);
						opacity: 0.9;
					}
				}
			}
			
			.room-desc {
				font-size: $font-sm;
				color: $text-secondary;
				margin-bottom: $spacing-xs;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
				line-height: 1.4;
			}
			
			.room-meta {
				display: flex;
				gap: $spacing-base;
				
				.meta-item {
					display: flex;
					align-items: center;
					gap: 4px;
					font-size: $font-xs;
					color: $text-secondary;
				}
			}
		}
	}
}

// 加载更多/没有更多
.load-more,
.no-more {
	padding: $spacing-lg 0;
	text-align: center;
	
	.load-more-text,
	.no-more-text {
		font-size: $font-sm;
		color: $text-secondary;
	}
}

// 空状态
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 80px $spacing-base;
	
	.empty-text {
		margin-top: $spacing-lg;
		font-size: $font-lg;
		color: $text-secondary;
	}
}
</style>

